//按照指定primaryKey去合并两个对象

import { toRaw } from "vue";

export function mergeFilteredData(original, filtered, exclude, primaryKey) {
  const excludeArray = exclude ? exclude.split(" ") : [];

  function merge(obj1, obj2) {
    for (let key in obj2) {
      if (excludeArray.includes(key)) {
        continue;
      }

      if (typeof obj1[key] === "object" && typeof obj2[key] === "object") {
        merge(obj1[key], obj2[key]);
      } else {
        obj1[key] = obj2[key];
      }
    }
  }

  function findAndMerge(originalArray, filteredItem) {
    const primaryKeyValue = filteredItem[primaryKey];
    const originalItem = originalArray.find(item => item[primaryKey] === primaryKeyValue);
    if (originalItem) {
      merge(originalItem, filteredItem);
    }
  }

  if (Array.isArray(original) && Array.isArray(filtered)) {
    filtered.forEach(filteredItem => findAndMerge(original, filteredItem));
  } else if (typeof original === "object" && typeof filtered === "object") {
    merge(original, filtered);
  }

  return original;
}
//根据指定key扁平化
export function flattenDataByKeys(data, keys) {
  const keyArray = keys.split(" ");

  function recursiveFlatten(obj, result = {}) {
    if (Array.isArray(obj)) {
      obj.forEach(item => recursiveFlatten(item, result));
    } else if (typeof obj === "object" && obj !== null) {
      let hasKey = keyArray.some(key => obj.hasOwnProperty(key));
      let resultKey = keyArray
        .map(key => obj[key])
        .filter(Boolean)
        .join("_");

      if (hasKey && resultKey) {
        result[resultKey] = obj;
      }

      for (let key in obj) {
        recursiveFlatten(obj[key], result);
      }
    }
    return result;
  }

  return recursiveFlatten(data);
}
/**
 *
 * @param source 数据源
 * @param target 目标数据
 * @param mappings 映射对象
 * @param template 模板数据，补全source缺失的字段
 * @returns updateTarget函数，用于watch进行数据更新
 */
export function initializeMapping(source, target, mappings, template) {
  //去空，不知道为什么会影响原始数据，这块数据合并有点复杂
  let maps = Object.keys(mappings || {})
    .filter(k => mappings[k] !== null && mappings[k] !== "")
    .reduce((a, k) => ({ ...a, [k]: mappings[k] }), {});
  const updateTarget = () => {
    // 如果映射关系C为空或没有定义，则直接赋值，并补充模板D中的字段
    if (!maps || Object.keys(maps).length === 0) {
      Object.assign(target, source);
      for (const key in template) {
        if (!(key in target)) {
          target[key] = template[key];
        }
      }
    } else {
      // 映射关系C中定义的字段
      for (const [targetKey, sourcePath] of Object.entries(maps)) {
        const sourceKeys = (sourcePath as string).split(".");
        let value = source;
        for (const key of sourceKeys) {
          value = value[key];
          if (value === undefined) break;
        }
        target[targetKey] = value;
      }
      // 映射关系C中未定义的字段
      for (const key in source) {
        if (!Object.values(maps).includes(key)) {
          target[key] = source[key];
        }
      }
      // 补充模板D中的字段
      for (const key in template) {
        if (!(key in target)) {
          target[key] = template[key];
        }
      }
    }
  };

  // 初始化B
  updateTarget();
  return updateTarget; // 返回更新函数
}
export function isEmpty(obj) {
  // Get the raw value of the object
  const rawObj = toRaw(obj);

  // Check if the raw object is null or undefined
  if (rawObj == null) {
    return true;
  }

  // Check if the raw object is an array or a string with length 0
  if (Array.isArray(rawObj) || typeof rawObj === "string") {
    return rawObj.length === 0;
  }

  // Check if the raw object is an object with no own properties
  if (typeof rawObj === "object") {
    return Object.keys(rawObj).length === 0;
  }

  // If none of the above conditions are met, the object is not empty
  return false;
}
